package com.sc.smartcommunity.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.sc.smartcommunity.common.Result;
import com.sc.smartcommunity.domain.User;
import com.sc.smartcommunity.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理接口", description = "提供用户注册、登录、鉴权等功能")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户通过用户名、手机号和密码进行注册")
    public Result<String> register(@RequestBody User user) {
        boolean success = userService.register(user.getUsername(), user.getPhone(), user.getPassword());
        return success ? Result.success("注册成功") : Result.error("用户名或手机号已存在");
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户通过手机号和密码进行登录")
    public Result<String> login(@RequestBody User user) {
        boolean success = userService.login(user.getPhone(), user.getPassword());
        if (success) {
            // 登录并生成 token（用手机号作为登录ID）
            StpUtil.login(user.getPhone());
            return Result.success(StpUtil.getTokenValue());
        }
        return Result.error("手机号或密码错误");
    }

    @GetMapping("/logout")
    @Operation(summary = "退出登录", description = "清除用户登录状态")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("退出成功");
    }

}
